package jh.com.jhappbf.datamanager;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.PixAndDpUtil;


/**
 * @author : wwh
 * e-mail  : 953889276@qq.com
 * time    : 2019-7-5 10:00:24
 * desc    :
 */
public class FieldsSelectActivity extends AbActivity implements
        OnMenuItemClickListener, OnItemClickListener {

    @BindView(R.id.fields_add_edit)
    EditText fieldsAddEdit;
    @BindView(R.id.fields_add_btn)
    Button fieldsAddBtn;
    @BindView(R.id.fields_list)
    SwipeMenuListView fieldsList;
    @BindView(R.id.title_comeback_img)
    ImageView titleComebackImg;
    @BindView(R.id.title_tip)
    TextView titleTip;
    private List<String> mData;
    private List<String> mShowData;
    private ArrayAdapter<String> mAdapter;
    private String flag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.activity_fields_select);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        mData = new ArrayList<>();
        mShowData = new ArrayList<>();
        Intent intent = getIntent();
        flag = intent.getStringExtra("flag");
        if (flag != null && flag.length() > 0) {
            if ("f".equalsIgnoreCase(flag)) {
                titleTip.setText("发货选择");
            } else if ("s".equalsIgnoreCase(flag)) {
                titleTip.setText("收货选择");
            }
            getFieldValue();
        }
        SwipeMenuCreator creator = menu -> {
            SwipeMenuItem item = new SwipeMenuItem(this);
            item.setTitle(R.string.Address_select);
            item.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9, 0xCE)));
            item.setWidth(PixAndDpUtil.dp2px(80, this));
            item.setTitleSize(18);
            item.setTitleColor(Color.WHITE);
            menu.addMenuItem(item);

            SwipeMenuItem deleteItem = new SwipeMenuItem(this);
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
            deleteItem.setWidth(PixAndDpUtil.dp2px(80, this));
            deleteItem.setTitleSize(18);
            deleteItem.setIcon(R.drawable.history_item_delete);
            deleteItem.setTitleColor(Color.WHITE);
            menu.addMenuItem(deleteItem);
        };
        fieldsList.setMenuCreator(creator);
        fieldsList.setOnItemClickListener(this);
        fieldsList.setOnMenuItemClickListener(this);
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setDataToUi(fieldsAddEdit.getText().toString());
            }
        };
        fieldsAddEdit.addTextChangedListener(textWatcher);
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mShowData);
        fieldsList.setAdapter(mAdapter);
    }


    @OnClick({R.id.fields_add_btn, R.id.title_comeback_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fields_add_btn:
                addItem(fieldsAddEdit.getText().toString().trim());
                break;
            case R.id.title_comeback_img:
                finish();
                break;
            default:


        }
    }

    private void addItem(String item) {
        if (item.length() == 0) {
            return;
        }
        if (mData.contains(item)) {
            Toast.makeText(this, "该数据已存在不能重复添加", Toast.LENGTH_SHORT).show();
        }
        String methodName = "addField";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("field");
        param.add("value");
        value.add(flag);
        value.add(item);
        Listener<String> listener = response -> {
            JSONObject object = JsonHelper.getJsonObject(response);
            if (object != null) {
                String result = object.optString("result");
                String memo = object.optString("memo");
                if ("true".equals(result)) {
                    Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
                    mData.add(item);
                    mShowData.add(item);
                    mAdapter.notifyDataSetChanged();
                } else {

                    Toast.makeText(this, memo, Toast.LENGTH_SHORT).show();
                }
            }
        };
        ErrorListener errorListener = error -> {
            Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }

    @Override
    public void onMenuItemClick(int position, SwipeMenu arg1, int index) {
        String item = mShowData.get(position);
        switch (index) {
            case 0:
                selectItem(item);
                break;
            case 1:
                deleteItem(item);
                break;
            default:
                break;
        }

    }

    private void deleteItem(String item) {
        delete(flag, item);
    }

    private void selectItem(String item) {
        Intent intent = new Intent();
        intent.putExtra("result", item);
        setResult(0x0001, intent);
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String item = mShowData.get(position);
        selectItem(item);
    }

    /**
     * 删除cizu表里的某一条记录
     *
     * @param flag  h(货名)，f(发货)，s(收货),l(类型)等
     * @param value 记录的值
     */
    private void delete(String flag, final String value) {
        String methodName = "deleteField";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("fieldName");
        params.add("value");
        values.add(flag);
        values.add(value);
        Listener<String> listener = response -> {
            JSONObject object = JsonHelper.getJsonObject(response);
            if (object != null) {
                String result = object.optString("result");
                String memo = object.optString("memo");
                if ("true".equals(result)) {
                    mShowData.remove(value);
                    mData.remove(value);
                    mAdapter.notifyDataSetChanged();
                    Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(this, memo, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "删除失败，请重试", Toast.LENGTH_SHORT).show();
            }

        };
        ErrorListener errorListener = volleyError -> Toast.makeText(this, "网络异常！", Toast.LENGTH_SHORT).show();

        VolleyCallWebService webService = new VolleyCallWebService(methodName, params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }

    /**
     * 获取cizu表里所有的货名，收发货，类型等字段
     */
    private void getFieldValue() {
        mData.clear();
        mShowData.clear();
        String methodName = "getFieldValue";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("fieldName");
        value.add(flag);
        Listener<String> listener = response -> {
            List<JSONObject> objectList = JsonHelper.getJsonObjects(response);

            for (JSONObject object : objectList) {
                mData.add(object.optString("cczz"));
            }
            mShowData.addAll(mData);
//            mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mShowData);
//            fieldsList.setAdapter(mAdapter);
            mAdapter.notifyDataSetChanged();
        };
        ErrorListener errorListener = volleyError -> Toast.makeText(this, "网络异常！", Toast.LENGTH_SHORT).show();

        VolleyCallWebService webService = new VolleyCallWebService(methodName, param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(this).addRequest(webService);
    }

    /**
     * 设置查询的数据到界面
     *
     * @param content con
     */
    private void setDataToUi(String content) {
        mShowData.clear();
        for (String item : mData) {
            if (item.contains(content.toUpperCase())
                    || item.contains(content.toLowerCase())) {
                mShowData.add(item);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        getFieldValue();
//
////        fieldsList.requestFocus();
//    }
}
